package io.esirong.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 相机采样数据转换成图像数据
 */
public class CameraData2BitmapUtils {
    public static Bitmap getBitmap(byte[] data, int w, int h) {
        try {
            //格式成YUV格式
            YuvImage yuvimage = new YuvImage(data, ImageFormat.NV21, w, h, null);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, w, h), 100, baos);
            Bitmap bitmap = bytes2Bitmap(baos.toByteArray());
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap getBitmap(byte[] data, int srcW, int srcH, int srcAngle, int newW, int newH) {
        try {
            Bitmap bitmap = getBitmap(data, srcW, srcH);
            if (bitmap != null) {
                //旋转图片
                bitmap = BitmapUtils.rotateBitmap(bitmap, -1 * srcAngle);
                //裁剪图片
                float ratio = Math.max((float) newW / (float) srcW, (float) newH / (float) srcH);
                bitmap = BitmapUtils.scaleBitmap(bitmap, ratio);
                //圆形裁剪
                bitmap = BitmapUtils.circleBitmapCenter(bitmap);
            }
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap bytes2Bitmap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    public static void saveImage(Bitmap bmp) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "pic");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
